package com.miss.spjyx.network

import android.content.Context
import android.util.Log
import android.widget.Toast
import com.miss.spjyx.model.BaseRes
import com.miss.spjyx.model.Danju
import retrofit2.Call
import retrofit2.Callback
import retrofit2.HttpException
import retrofit2.Response
import java.lang.Exception

/**
 * 通用请求
 *
 * @author wl
 * @since 2019/08/31 13:53
 */
abstract class CommonCallback<T>(private val ctx: Context) : Callback<BaseRes<T>> {
    override fun onFailure(call: Call<BaseRes<T>>, t: Throwable) {
        Log.w("WL_request", t)
        if (t is HttpException) {
            onError(t.code().toString(), t.message ?: "请求出错了")
        }
        onError("-1", t.message ?: "请求出错了")
        onDone()
    }

    override fun onResponse(call: Call<BaseRes<T>>, response: Response<BaseRes<T>>) {
        Log.w("WL_request", response.toString())
        if (response.isSuccessful && response.body() != null) {
            if (response.body()!!.success) {
                onData(response.body()!!.data)
            } else {
                onError("-2", response.body()!!.msg ?: "请求出错了")
            }
        } else {
            onError(response.code().toString(), response.message())
        }
        onDone()
    }

    abstract fun onData(data: T?)

    open fun onError(code: String, msg: String) {
        try {
            Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    open fun onDone() {

    }
}